package org.jeecg.modules.error.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.error.entity.ErrorRecord;
import org.jeecg.modules.error.mapper.ErrorRecordMapper;
import org.jeecg.modules.error.service.IErrorRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;

/**
 * @Description: ErrorRecord
 * @Author: jeecg-boot
 * @Date:   2019-06-04
 * @Version: V1.0
 */
@Slf4j
@Service
public class ErrorRecordServiceImpl extends ServiceImpl<ErrorRecordMapper, ErrorRecord> implements IErrorRecordService {

    private static final int des = 1;//脱敏错误


    @Autowired
    ErrorRecordMapper errorRecordMapper;

    @Override
    public Boolean recordSch(String title, String context, int level) {
        return record(title, context, level, des, null);
    }

    @Override
    public Boolean recordSch(String title, String context, int level, String memo) {
        return record(title, context, level, des, memo);
    }

    private Boolean record(String title, String context, int level, int type, String memo) {
        Boolean result = validate(title, context, level);
        if (false == result) {
            return result;
        }
        return recordDB(getErrorDO(title, context, level, type, memo));
    }

    private Boolean recordDB(ErrorRecord errorRecord) {
        try {
            int nt = errorRecordMapper.insert(errorRecord);
            if (nt == 0) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            log.error("错误异常表记录失败!",e);
            return false;
        }
    }

    private Boolean validate(String title, String context, int level) {
        if (StringUtils.isEmpty(title)) {
            return false;
        }
        if (null == context) {
            return false;
        }
        if (0 == level) {
            return false;
        }

        return true;
    }

    private ErrorRecord getErrorDO(String title, String context, int level, int type, String memo) {
        ErrorRecord errorRecord = new ErrorRecord();
        errorRecord.setErrorContext(context);
        errorRecord.setErrorTitle(title);
        errorRecord.setErrorMemo(memo);
        errorRecord.setErrorLevel(level);
        errorRecord.setErrorType(type);
        errorRecord.setErrorServerIp(getIP());
        errorRecord.setCreateTime(new Date());
        return errorRecord;
    }

    private String getIP() {
        try {
            //分布式后在考虑获取ip
            return  "";
//            return CommonUtils.getLocalIpV4(null);
        } catch (Exception e) {
        }
        return "";
    }

}
